﻿using System;
using System.Buffers;
using System.IO;
using System.Net.Security;
using System.Text;
using Deer.Extension;
using Letter.IO.Binary;
using Letter.Net.Tcp;

namespace Telex;

sealed class RpcServerConnection : ARcpConnection
{
    public RpcServerConnection(ref ConnectionFixedConfig config) : base(ref config)
    {
    }

    public RpcServerConnection(ref ConnectionFixedConfig config, SslOptions sslOptions, Func<Stream, SslStream> sslStreamFactory)
        : base(ref config, sslOptions, sslStreamFactory)
    {
    }

    protected override void OnActive()
    {
        base.OnActive();
    }

    protected override void OnMessage(ReadOnlySequence<byte> buf)
    {
        var reader = buf.ToBytesReader();
        var command = reader.ReadUInt8();
        switch (command)
        {
            case Command.SECRET_KEY_REQ:
                this.OnRcvSecretkeyReqMessage(ref reader);
                break;
            case Command.SYNC_HOST_OPTIONS:
                this.OnRcvSyncHost(ref reader);
                break;
            default:
                OnRcvSocketMessage(command, ref reader);
                break;
        }
    }

    private void OnRcvSecretkeyReqMessage(ref BytesReader reader)
    {
        var secretkeyBuf = reader.ReadBuffer((int)reader.ReadableLength);
        var secretkey = Encoding.UTF8.GetString(secretkeyBuf.ToArray());
        if (secretkey == this.secretkey)
        {
            this.Pipelines.Output.DeliverSecretkeyResPack(1);
            this.Pipelines.Output.DeliverHostOptions(this.localHost);
        }
        else
        {
            this.Pipelines.Output.DeliverSecretkeyResPack(0);
            this.CloseAsync().Sync();
        }
    }
}